<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------
// | Author: JiYun Date:2019-05-08 Time:18:13
// +----------------------------------------------------------------------

namespace app\common\service\system;

use app\common\service\BaseService;
use app\common\model\system\SystemUserToken as SystemUserTokenModel;

/**
 * Class SystemUserToken
 * @author JiYun On 2019/05/09
 * @package app\common\service\system
 */
final class SystemUserToken extends BaseService
{
    // 超时时间为两个小时
    private $expire = 60 * 60 * 2;
    
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * 生成Token
     * @author JiYun On 2019/05/09
     * @return string
     */
    private function genericToken()
    {
        return md5(uniqid()) . md5(uniqid());
    }
    
    /**
     * 将生成的Token保存
     * @author JiYun On 2019/05/09
     * @param string $userId
     * @param string $token
     */
    private function saveData($userId = '', $token = '')
    {
        $time = time();
        
        $tokenData = [
            'user_id'     => $userId,
            'expire_time' => $time + $this->expire,
            'create_time' => $time,
            'token'       => $token
        ];
        
        $userToken = new SystemUserTokenModel();
        $userToken->saveData($tokenData);
    }
    
    /**
     * 获取Token
     * @author JiYun On 2019/05/09
     * @param string $userId
     * @return string
     */
    public function getToken($userId = '')
    {
        $token = $this->genericToken();
        
        $this->saveData($userId, $token);
        
        return $token;
    }
    
    /**
     * 设置token过期
     * @author JiYun On 2019/05/09
     * @param string $token
     * @return bool
     */
    public function expireToken($token = '')
    {
        $where = [
            'token' => $token
        ];
    
        $data = [
            'expire_time' => time()
        ];
        
        $userToken = new SystemUserTokenModel();
        return $userToken->expireToken($where, $data);
    }
}
